const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const empty = require('../utils/empty')
const User = require('../model/UserModel')
const Menu = require('../model/MenuModel')
const Role = require('../model/RoleModel')
const API_SECRETORKEY = process.env.API_SECRETORKEY
const { list2tree } = require('../utils/utils')
/**
 * 登录
 */
exports.login = async (req, res) => {
  let { username, password } = req.body
  // 判断是否存在
  if (empty(username) || empty(password)) {
    throw new Error('用户名/密码不能为空')
  }
  // 去除空格
  username = username.trim()
  password = password.trim()

  // 校验用户是否存在
  const user = await User.findOne({ name: username }, 'name password')
  // const exist = await UserService.checkExist(username)
  if (!user || empty(user.name)) {
    throw new Error('用户不存在')
  }

  // 比较密码是否匹配
  const isMatch = bcrypt.compareSync(password, user.password)
  if (!isMatch) {
    throw new Error('密码错误')
  }
  // 签发token
  const token = jwt.sign({ username }, API_SECRETORKEY, {
    expiresIn: '1Y'
  })

  res.json({
    code: 20000,
    message: '登录成功',
    token
  })
}

/**
 * 登出
 */
exports.logout = (req, res) => {
  // 记录日志
  if (req.user) {
    console.log('username =', req.user, '退出成功')
  }
  res.json({
    message: '退出成功',
    code: 20000
  })
}

/**
 * 获取用户信息
 */
exports.info = async (req, res) => {
  if (req.isLogined) {
    const username = req.user
    const user = await User.findOne({ name: username }, { password: 0 })
    res.json({
      message: '获取用户信息',
      data: user,
      code: 20000
    })
  } else {
    throw new Error('未登录')
  }
}

/**
 * 获取当前用户的路由信息
 */
exports.routes = async (req, res) => {
  const username = req.user
  const user = await User.findOne({ name: username }).lean()
  console.log('🚀 ~ file: auth.controller.js ~ line 83 ~ exports.routes= ~ user', user)
  const roleIds = user.roles
  console.log('🚀 ~ file: auth.controller.js ~ line 85 ~ exports.routes= ~ roleIds', roleIds)
  const roles = await Role.find({ _id: { $in: roleIds } }).lean()
  console.log('🚀 ~ file: auth.controller.js ~ line 87 ~ exports.routes= ~ roles', roles)
  let menuIds = []
  roles.forEach((r) => {
    console.log('🚀 ~ file: auth.controller.js ~ line 90 ~ exports.routes= ~ r.menuCheckedKeys', r.menuCheckedKeys)
    menuIds = menuIds.concat(r.menuCheckedKeys).concat(r.menuHalfCheckedKeys)
  })
  console.log('🚀 ~ file: auth.controller.js ~ line 90 ~ exports.routes= ~ menuIds', menuIds)
  const menuTree = await Menu.find({
    type: 'MENU',
    _id: { $in: menuIds }
  }, '-type -menuType -__v -code').lean()
  const { treeData } = list2tree(menuTree, null)
  if (req.isLogined) {
    res.json({
      code: 20000,
      message: '获取用户的路由信息',
      data: {
        items: treeData
      }
    })
  } else {
    throw new Error('未登录')
  }
}
/**
 * 获取当前用户的路由信息
 */
exports.btns = async (req, res) => {
  const username = req.user
  const user = await User.findOne({ name: username }).lean()
  console.log('🚀 ~ file: auth.controller.js ~ line 83 ~ exports.routes= ~ user', user)
  const roleIds = user.roles
  console.log('🚀 ~ file: auth.controller.js ~ line 85 ~ exports.routes= ~ roleIds', roleIds)
  const roles = await Role.find({ _id: { $in: roleIds } }).lean()
  console.log('🚀 ~ file: auth.controller.js ~ line 87 ~ exports.routes= ~ roles', roles)
  let btnIds = []
  roles.forEach((r) => {
    console.log('🚀 ~ file: auth.controller.js ~ line 90 ~ exports.routes= ~ r.menuCheckedKeys', r.menuCheckedKeys)
    btnIds = btnIds.concat(r.menuCheckedKeys)
  })
  const btns = await Menu.find(
    {
      type: 'BUTTON',
      _id: { $in: btnIds }
    },
    'title code'
  ).lean()
  if (req.isLogined) {
    res.json({
      code: 20000,
      message: '获取用户的按钮',
      data: {
        items: btns
      }
    })
  } else {
    throw new Error('未登录')
  }
}
